package com.bw.documents.local

import androidx.lifecycle.viewModelScope
import com.bawei.library_mvi.model.BaseViewModel
import com.bawei.module_documents.local.LocalFileIntent
import com.bawei.module_documents.local.LocalFileState
import com.bawei.module_documents.manager.FileIntent
import com.bawei.module_documents.manager.FileState
import com.bawei.module_documents.manager.model.FileService
import com.blankj.utilcode.util.LogUtils
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

class LocalViewModel : BaseViewModel<LocalFileIntent>() {

    private val localRepo: LocalRepo by lazy{ LocalRepo() }
    private val _states = MutableStateFlow<LocalFileState>(LocalFileState.Init)//MutableStateFlow可变
    val states: StateFlow<LocalFileState>
        get() = _states

    //查询本地文件
    fun scanFiles(){
        viewModelScope.launch {
            localRepo.scanLocalDocuments()
                .catch { t : Throwable->
                    LogUtils.e("errorMsg:${t.message}") }
                .collect{
                    _states.value = LocalFileState.LocalFileSuccess(it)
                }
        }
    }

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is LocalFileIntent.LocalFileDataIntent ->  scanFiles()//查询本地文件
                }
            }
        }
    }
}